package com.ymdx.action;

import com.opensymphony.xwork2.ModelDriven;
import com.ymdx.entity.Admin;
import com.ymdx.service.AdminService;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.struts2.convention.annotation.Action;
import org.apache.struts2.convention.annotation.Result;

import javax.annotation.Resource;

/**
 * Created by yangliwei on 2017/8/18.
 */
public class AdminAction extends GenericActionSupport implements ModelDriven<Admin> {
    private Admin admin;
    private String oldPassword;

    @Resource
    private AdminService adminService;

    @Action(value = "/admin/login", results = @Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message"
    }))
    public String login() {
        String name = admin.getAdminName();
        String password = admin.getAdminPassword();
        if (StringUtils.isAnyBlank(name, password)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        String result = String.valueOf(DigestUtils.md5Hex(name + password));
//        防止注入 直接找数据库第一条数据和admin匹配
        Admin oldAdmin = adminService.getById(Admin.class, 1L);
        if (!oldAdmin.getAdminPassword().equalsIgnoreCase(result)) {
            responseTool.setStatus(0);
            responseTool.setCode("admin_error_password");
            return SUCCESS;
        }
        session.put("admin", admin.getAdminName());
        responseTool.setStatus(1);
        return SUCCESS;
    }

    @Action(value = "/admin/edit", results = @Result(name = SUCCESS, type = JSON, params = {
            "root", "responseTool",
            "includeProperties", "status,code,message"
    }))
    public String edit() {
        String password = admin.getAdminPassword();
        if (StringUtils.isAnyBlank(password, oldPassword)) {
            responseTool.setStatus(0);
            responseTool.setCode("parameter_empty");
            return SUCCESS;
        }
        Admin oldAdmin = adminService.getById(Admin.class, 1L);
        if (!DigestUtils.md5Hex(oldAdmin.getAdminName() + oldPassword).equals(oldAdmin.getAdminPassword())) {
            responseTool.setStatus(0);
            responseTool.setCode("admin_error_password");
            return SUCCESS;
        }
        oldAdmin.setAdminPassword(DigestUtils.md5Hex(oldAdmin.getAdminName() + password));
        adminService.save(oldAdmin);
        responseTool.setStatus(1);
        return SUCCESS;
    }


    @Override
    public Admin getModel() {
        if (admin == null) {
            admin = new Admin();
        }
        return admin;
    }

    public String getOldPassword() {
        return oldPassword;
    }

    public void setOldPassword(String oldPassword) {
        this.oldPassword = oldPassword;
    }
}
